//
//  DownLoadManager.m
//  Four_Fit_New
//
//  Created by lanou on 16/7/21.
//  Copyright © 2016年 xmaz. All rights reserved.
//

#import "DownLoadManager.h"
@interface DownLoadManager()<NSURLSessionDownloadDelegate>

@property (nonatomic,strong)NSMutableArray *dataSource;

@property (nonatomic,strong)NSURLSession *session;
@property (nonatomic,strong)NSURLSessionDownloadTask *task;
@property (nonatomic,strong)NSTimer *timer;



@property (nonatomic,copy)Load loading;
@property (nonatomic,copy)Comp complted;
@property (nonatomic,strong)NSString *filePath;

@end

@implementation DownLoadManager
- (NSTimer *)timer{
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
    }
    return _timer;
}
- (NSString *)filePath{
    if (!_filePath) {
        _filePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    }
    return _filePath;
}
- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
        
    }
    return _dataSource;
}
- (NSURLSession *)session{
    static dispatch_once_t onceToKen;
    dispatch_once(&onceToKen, ^{
        _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
    });
    return _session;
}

- (instancetype)initWithUrlArr:(NSMutableArray *)urlArr {
    
    self = [super init];
    
    if (self) {
        self.dataSource = urlArr;
    }
    return self;
}


- (void)startDownLoadWithCount:(NSInteger)number{
    for (int i = 0; i<number; i++) {
        NSURLSessionDownloadTask *task = [self.session downloadTaskWithURL:[NSURL URLWithString:self.dataSource[0]]];
        [task resume];
        [self.timer fire];
        [self.dataSource removeObjectAtIndex:0];
    }
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    
    NSString *name = downloadTask.response.suggestedFilename;
    NSString *newPath = [self.filePath stringByAppendingPathComponent:name];
    [[NSFileManager defaultManager]moveItemAtPath:location.pathExtension toPath:newPath error:nil];
    if (self.loading) {
        self.loading(newPath);
    }
    
}
- (void)timeAction{
    if (self.complted&&[self.dataSource count]==0) {
        self.complted();
        [self.timer invalidate];
        self.timer = nil;
    }
    
}
- (void)downLoad:(Load)loading Finish:(Comp)comple{
    self.loading = loading;
    self.complted = comple;
}


@end
